// Node.c

#include	"Node.h"

void NodeInit(struct sNode *pNode, char letter) {
    pNode->pChild = NULL;
    pNode->pNext = NULL;
    pNode->pParent = NULL;
    pNode->pPrev = NULL;
    return;
}

struct sNode *NodeGetRoot( struct sNode *pNode ){
    struct sNode *pTmp;
    for( pTmp = pNode ; pTmp != NULL ; pTmp = pTmp->pParent ){
        if( pTmp->pParent == NULL ){
            return pTmp;
        }
    }
    return NULL;
}

int NodeContains( struct sNode *pNode, struct sNode *pTest ){
    return NodeContainsPreOrderCN( NodeGetRoot( pNode ), pTest );
}

int NodeContainsPreOrderCN( struct sNode *pNode, struct sNode *pTest ){
    if( pNode == NULL ){
        return 0;
    }
    if( pNode == pTest ){
        return 1;
    }
    if( NodeContainsPreOrderCN( pNode->pChild, pTest ) ){
        return 1;
    }
    if( NodeContainsPreOrderCN( pNode->pNext, pTest ) ){
        return 1;
    }
    return 0;
}

int NodeAdd(struct sNode *pNode, struct sNode *pNew) {
    struct sNode *pTmp;
    
    if( NodeContains( pNode, pNew ) ){
        return 0;
    }
    if (pNode->pChild == NULL) {
        pNode->pChild = pNew;
        // pNew->pChild = NULL;
        pNew->pPrev = NULL;
        pNew->pParent = pNode;
        pNew->pNext = NULL;
        return 1;
    } else {
        for (pTmp = pNode->pChild; pTmp != NULL; pTmp = pTmp->pNext) {
            if (pTmp->pNext == NULL) {
                pTmp->pNext = pNew;
                // pNew->pChild = NULL;
                pNew->pPrev = pTmp;
                pNew->pParent = pTmp->pParent;
                pNew->pNext = NULL;
                return 1;
            }
        }
        return 0;
    }
    return 0;
}

int NodeDel(struct sNode *pNode, struct sNode *pOld) {
    struct sNode *pTmp;

    if (pNode->pChild == NULL) {
        return 0;
    } else if (pNode->pChild == pOld) {
        pNode->pChild = pOld->pNext;
        if (pOld->pNext != NULL) {
            pOld->pNext->pPrev = NULL;
        }
        // pOld->pChild = NULL;
        pOld->pParent = NULL;
        pOld->pPrev = NULL;
        pOld->pNext = NULL;
        return 1;
    } else {
        for (pTmp = pNode->pChild; pTmp != NULL; pTmp = pTmp->pNext) {
            if (pTmp->pNext == pOld) {
                pTmp->pNext = pOld->pNext;
                if (pOld->pNext != NULL) {
                    pOld->pNext->pPrev = pOld->pPrev;
                }
                //  pOld->pChild = NULL;
                pOld->pParent = NULL;
                pOld->pPrev = NULL;
                pOld->pNext = NULL;
                return 1;
            }
        }
        return 0;
    }
    return 0;
}

int NodeMove(struct sNode *pNode, struct sNode *pMove) {
    if (NodeDel(pNode, pMove)) {
        return NodeAdd(pNode, pMove);
    }
    return 0;
}

